package com.atguigu.tingshu.album.receiver;

import com.alibaba.fastjson.JSON;
import com.atguigu.tingshu.album.service.TrackInfoService;
import com.atguigu.tingshu.common.constant.KafkaConstant;
import com.atguigu.tingshu.common.result.Result;
import com.atguigu.tingshu.vo.album.TrackStatMqVo;
import org.apache.kafka.clients.consumer.ConsumerRecord;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.kafka.annotation.KafkaListener;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import java.util.concurrent.TimeUnit;

/**
 * @author atguigu-mqx
 * @ClassName TrackReceiver
 * @description: TODO
 * @date 2023年12月29日
 * @version: 1.0
 */
@Component
public class TrackReceiver {

    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private TrackInfoService trackInfoService;

    /**
     * 监听声音播放量消息
     * @param record
     */
    @KafkaListener(topics = KafkaConstant.QUEUE_TRACK_STAT_UPDATE)
    public void trackUpdate(ConsumerRecord<String,String> record){
        //  获取消息数据
        String jsonData = record.value();
        //  判断
        if (!StringUtils.isEmpty(jsonData)){
            //  数据类型转换
            TrackStatMqVo trackStatMqVo = JSON.parseObject(jsonData, TrackStatMqVo.class);
            //  setnx key value;
            String key = trackStatMqVo.getBusinessNo();
            Boolean exist = this.redisTemplate.opsForValue().setIfAbsent(key, "ok", 10, TimeUnit.MINUTES);
            try {
                //  判断exist=true; 第一次消费，false: 有消费者消费了.
                if (exist){
                    //  更新专辑，声音播放量.
                    trackInfoService.updateStat(trackStatMqVo.getAlbumId(),trackStatMqVo.getTrackId(),trackStatMqVo.getStatType(),trackStatMqVo.getCount());
                } else {
                    //  有消费过了. 签收：
                }
            } catch (Exception e) {
                this.redisTemplate.delete(key);
            }
        }

    }
}
